import { Component, OnInit } from '@angular/core';
import { HttpService } from 'src/app/service/http.service';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-patient-my-appointments',
  templateUrl: './patient-my-appointments.page.html',
  styleUrls: ['./patient-my-appointments.page.scss'],
})
export class PatientMyAppointmentsPage implements OnInit {
  dataList = [];
  loadTimes = 0;
  stopLoad = false;
  showNone = false;
  weekDays = [
    '星期日',
    '星期一',
    '星期二',
    '星期三',
    '星期四',
    '星期五',
    '星期六'
  ];
  sysLang = '';

  constructor(
    private httpService: HttpService,
    private router: Router,
    private translate: TranslateService
  ) { }

  ngOnInit() {
    this.sysLang = this.translate.getBrowserCultureLang().toLowerCase();
  }

  async ionViewDidEnter() {
    await this.getOrderList('fresh', 0);
  }

  public async getOrderList(aType, aLoadtimes) {
    const aOffset = aLoadtimes * 10;
    const aUserId = localStorage.getItem('userId');
    const result: any = await this.httpService.get()
      .setPath('/order/orderBookingList')
      .setQuery({
        patientUserId: aUserId,
        orderType: 1,
        orderBooking: 2,
        doctorType: 2,
        offset: aOffset,
        limit: 10
      })
      .request();
    if (result.status === 0) {
      if (aType === 'fresh') {
        this.dataList = result.data.rows;
      } else if (aType === 'infinite') {
        for (const item of result.data.rows) {
          this.dataList.push(item);
        }
      }
      for (const item of this.dataList) {
        item.order_time = `${item.start_time} - ${item.end_time.split(' ')[1]}`;
      }
      this.stopLoad = true;
      if (this.dataList.length === result.data.count) {
        this.showNone = true;
      }
    }
  }

  public async clickOrder(item) {
    if (item.dct_type === 3) {
      await this.router.navigate(['hospital-info'], {
        queryParams: {
          hospitalUserId: item.doctor_user_id,
          orderId: item.order_id,
          orderAccept: item.order_accept,
          viewType: 2
        }
      });
    } else {
      await this.router.navigate(['patient-appoint-details'], {
        queryParams: {
          orderTime: item.order_time.__zone_symbol__value,
          doctorId: item.doctor_user_id,
          orderId: item.id,
          orderStatus: item.order_accept
        }
      });
    }
  }

  public async doRefresh(event) {
    this.loadTimes = 0;
    await this.getOrderList('fresh', 0);
    if (!!this.stopLoad) {
      event.target.complete();
    }
  }

  public async loadData(event) {
    this.loadTimes += 1;
    await this.getOrderList('infinite', this.loadTimes);
    if (!!this.stopLoad) {
      event.target.complete();
    }
  }
}
